/*
*Copyright © 2019 XSNOW
*四川瑞韬科技有限公司
*http://www.ratotech.com.cn
*All rights reserved.
*/
package com.icesoft.xsnow.upms.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.icesoft.xsnow.common.security.annotation.Inner;
import com.icesoft.xsnow.framework.api.param.ICreate;
import com.icesoft.xsnow.framework.api.reponses.R;
import com.icesoft.xsnow.framework.api.util.ApiAssert;
import com.icesoft.xsnow.framework.controller.BaseController;
import com.icesoft.xsnow.upms.api.dto.UserInfo;
import com.icesoft.xsnow.upms.api.param.UserParam;
import com.icesoft.xsnow.upms.api.po.SysUser;
import com.icesoft.xsnow.upms.core.enums.UserEcodeEnum;
import com.icesoft.xsnow.upms.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @program: xsnow
 * @description: 用户表 前端控制器
 * @author xuefeng.gao
 * @create: 2019-05-27
 */
@RestController
@Validated
@RequestMapping(value = "user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(tags = {"SysUser"}, description = "用户表相关接口")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService userService;

    @ApiOperation("查询单个用户")
    @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path") })
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return success(userService.getById(id));
    }


    @ApiOperation("分页查询所有用户")
    @GetMapping("/page")
    public R page() {
        return success(userService.page(this.getPage()));
    }


    @ApiOperation("注册新用户")
    @PreAuthorize("@pms.hasPermission('sys:user:register')")
    @PostMapping("/register")
    public R register(@Validated({ICreate.class}) @RequestBody UserParam registerUser) {
        //判断用户名是否已注册
        int count =  userService.lambdaQuery().eq(SysUser::getUsername,registerUser.getUsername()).count();
        ApiAssert.isTrue(UserEcodeEnum.USERNAME_ALREADY_EXISTS, count == 0);
        //判断手机号是否已注册
        count =  userService.lambdaQuery().eq(SysUser::getPhone,registerUser.getPhone()).count();
        ApiAssert.isTrue(UserEcodeEnum.USER_PHONE_ALREADY_EXISTS, count == 0);
        //判断EMAIL是否已注册
        count =  userService.lambdaQuery().eq(SysUser::getEmail,registerUser.getEmail()).count();
        ApiAssert.isTrue(UserEcodeEnum.USER_EMAIL_ALREADY_EXISTS, count == 0);
        return success(userService.save(registerUser));
    }

    @ApiOperation("重置用户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path")
    })
    @PutMapping("/{id}/password")
    public R<Void> resetPwd(@PathVariable("id") Integer id) {
        userService.resetPwd(id);
        return success();
    }


    @ApiOperation("新增用户")
    @PreAuthorize("@pms.hasPermission('sys:user:add')")
    @PostMapping
    public R save(@Valid @RequestBody SysUser sysUser) {
        return success(userService.save(sysUser));
    }


    @ApiOperation("编辑用户")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('sys:user:edit')")
    public R update(@Valid @RequestBody SysUser sysUser) {
        //判断用户名是否已删除
        SysUser existUser = userService.getById(sysUser);
        ApiAssert.isTrue(UserEcodeEnum.USER_NOT_FOUND,existUser != null);
        //判断手机号是否已被其他用户注册
        int count =  userService.lambdaQuery().eq(SysUser::getPhone,sysUser.getPhone()).ne(SysUser::getId, sysUser.getId()).count();
        ApiAssert.isTrue(UserEcodeEnum.USER_PHONE_ALREADY_EXISTS, count == 0);
        //判断EMAIL是否已被其他用户注册
        count =  userService.lambdaQuery().eq(SysUser::getEmail,sysUser.getEmail()).ne(SysUser::getId, sysUser.getId()).count();
        ApiAssert.isTrue(UserEcodeEnum.USER_EMAIL_ALREADY_EXISTS, count == 0);


        return success(userService.updateById(sysUser));
    }


    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('sys:user:del')")
    public R removeById(@PathVariable Integer id) {
        return success(userService.removeById(id));
    }


    /**
     * 通过用户名查询用户、角色信息
     *
     * @param username 用户名
     * @return R
     */
    @Inner
    @GetMapping("/info/{username}")
    public R<UserInfo> info(@PathVariable("username") String username){
        SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername,username));
        ApiAssert.isTrue(UserEcodeEnum.USER_NOT_FOUND, ObjectUtil.isNotNull(user));
        UserInfo userInfo = userService.findUserInfo(user);
        return success(userInfo);
    }

}
